﻿using System;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using BluePortal.LiveID;

namespace BluePortal.QuikStart.Images
{
    public class AvatarHandler : IHttpHandler
    {
        public static string GetUrl(string loginName)
        {
            return "Images/AvatarHandler.ashx?user=" + loginName ;
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "image/jpeg";
                BluePortalMemberShipProvider ms = (BluePortalMemberShipProvider)Membership.Provider;
                string userName = string.Empty;
                if (context.Request["user"] != null)
                {
                    userName = context.Request["user"];
                }
                else
                {
                    userName = HttpContext.Current.User.Identity.Name;
                }

                MemoryStream memory = new MemoryStream(ms.GetAvatar(userName));
                Image bm = Bitmap.FromStream(memory);
                context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch
            {
                context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                Image bmnull = Bitmap.FromFile(context.Server.MapPath("~/Images/anonymous.jpg"));
                bmnull.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
